package com.nowcoder.community.controller.advice;

import com.nowcoder.community.controller.exception.PageErrorException;
import com.nowcoder.community.controller.exception.PageNotFoundException;
import com.nowcoder.community.controller.exception.RestPageErrorException;
import com.nowcoder.community.util.JsonBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@ControllerAdvice
public class DefaultControllerAdvice {

    @ExceptionHandler
    public ModelAndView handlePageNotFoundException(PageNotFoundException e) {
        return new ModelAndView("/error/404").addObject("msg", e.getMessage());
    }

    @ExceptionHandler
    public ModelAndView handlePageErrorException(PageErrorException e) {
        log.error("发生请求处理异常: " + e.getMessage());
        return new ModelAndView("/error/500").addObject("msg", e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler
    public JsonBody handleRestPageErrorException(RestPageErrorException e) {
        return JsonBody.error(e.getMessage());
    }
}
